package main

import (
	"fmt"
	"github.com/micro/cli/v2"
	"github.com/micro/go-micro/v2"
	"github.com/valyala/fasthttp"
	"log"
	"runtime"
	"time"

	"kop/framework/broker"
	"kop/framework/conf"
	"kop/libs/protobufrpc"
	"kop/libs/redis"
	"kop/modules/api/cron"
	"kop/modules/api/handler"
	"kop/modules/api/services"
	log2 "kop/util/log"
)

func main() {

	runtime.GOMAXPROCS(2)

	conf.Init()
	log2.SetLevel(conf.Log.Level)

	if err := redis.Init(conf.Redis.Address, conf.Redis.MaxIdle, conf.Redis.MaxActive); err != nil {
		panic(fmt.Errorf("redis error: %w", err))
	}

	cron.Cron()

	register()

	var srv = micro.NewService(
		micro.Action(func(c *cli.Context) error {

			if err := broker.Init(c.String("broker_address")); err != nil {
				return err
			}

			var port = c.String("server_address")
			if port == "" {
				port = "10001"
			}

			go checkRun(port)
			return fasthttp.ListenAndServe(":"+port, handler.Handler)
		}),
	)
	srv.Init()
}

func register() {

	protobufrpc.Register(new(services.AchievementService))
	protobufrpc.Register(new(services.ActivityService))
	protobufrpc.Register(new(services.BuildingService))
	protobufrpc.Register(new(services.CaptainService))
	protobufrpc.Register(new(services.ChatService))
	protobufrpc.Register(new(services.ConnectService))
	protobufrpc.Register(new(services.ConquerService))
	protobufrpc.Register(new(services.GuildService))
	protobufrpc.Register(new(services.ItemService))
	protobufrpc.Register(new(services.IslandService))
	protobufrpc.Register(new(services.MaidService))
	protobufrpc.Register(new(services.MailService))
	protobufrpc.Register(new(services.RingService))
	protobufrpc.Register(new(services.RoleService))
	protobufrpc.Register(new(services.StageService))
	protobufrpc.Register(new(services.TreasureService))
	protobufrpc.Register(new(services.ShopService))
	protobufrpc.Register(new(services.PortService))
	protobufrpc.Register(new(services.RankingService))
	protobufrpc.Register(new(services.WorldBossService))
	protobufrpc.Register(new(services.PayService))

}

func checkRun(port string) {

	for range time.NewTicker(time.Second).C {

		if _, _, err := fasthttp.Get(nil, fmt.Sprintf("http://127.0.0.1:%s/api", port)); err == nil {
			log.Println("Start API server Listening on [::]:" + port)
			break
		}
	}
}
